/**
 * @file
 * @brief 主模块：应用程序入口
 * @author
 * + 隐星魂 (Roy Sun) <xwos@xwos.tech>
 * @copyright
 * + Copyright © 2015 xwos.tech, All Rights Reserved.
 * > Licensed under the Apache License, Version 2.0 (the "License");
 * > you may not use this file except in compliance with the License.
 * > You may obtain a copy of the License at
 * >
 * >         http://www.apache.org/licenses/LICENSE-2.0
 * >
 * > Unless required by applicable law or agreed to in writing, software
 * > distributed under the License is distributed on an "AS IS" BASIS,
 * > WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * > See the License for the specific language governing permissions and
 * > limitations under the License.
 */

#include "../Board/std.h"
#include <xwos/osal/thd.h>
#include "gd32f10x_rcu.h"
#include "gd32f10x_gpio.h"

#define MAIN_THD_PRIORITY XWOS_SKD_PRIORITY_DROP(XWOS_SKD_PRIORITY_RT_MAX, 0)

static xwer_t main_task(void * arg);

__xwcc_aligned(8) xwu8_t main_thd_stack[4096] = {0};
const struct xwos_thd_desc main_thd_desc = {
        .attr = {
                .name = "main.thd",
                .stack = (xwstk_t *)main_thd_stack,
                .stack_size = sizeof(main_thd_stack),
                .stack_guard_size = XWOS_STACK_GUARD_SIZE_DEFAULT,
                .priority = MAIN_THD_PRIORITY,
                .detached = true,
                .privileged = true,
        },
        .func = main_task,
        .arg = NULL,
};
struct xwos_thd main_thd;
xwos_thd_d main_thdd;

xwer_t xwos_main(void)
{
        xwer_t rc;

        rc = xwos_thd_init(&main_thd, &main_thdd,
                           &main_thd_desc.attr,
                           main_thd_desc.func,
                           main_thd_desc.arg);
        if (rc < 0) {
                goto err_thd_init;
        }

        rc = xwos_skd_start_lc();
        if (rc < 0) {
                goto err_skd_start_lc;
        }

        return XWOK;

err_thd_init:
        BOARD_BUG();
err_skd_start_lc:
        BOARD_BUG();
        return rc;
}

static xwer_t main_task(void * arg)
{
        xwer_t rc;

        XWOS_UNUSED(arg);
        rc = XWOK;

        rcu_periph_clock_enable(RCU_GPIOC);
        gpio_init(GPIOC, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_13);
        while (!xwos_cthd_frz_shld_stop(NULL)) {
                gpio_bit_set(GPIOC, GPIO_PIN_13);
                xwos_cthd_sleep(xwtm_s(1));
                gpio_bit_reset(GPIOC, GPIO_PIN_13);
                xwos_cthd_sleep(xwtm_s(1));
        }
        return rc;
}
